package com.example.mongodb_learn;

import com.mongodb.client.*;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;

/**
 * mongodb操作测试类
 */
@Component
public class MongoTest {
    static MongoClient client;
    static   MongoDatabase database;
    static {
         client = MongoClients.create("mongodb://test:test@127.0.0.1:27017/test?directConnection=true&serverSelectionTimeoutMS=2000");
         database = client.getDatabase("test");

    }

    public static void main(String[] args) {
        MongoCollection<Document> collection = database.getCollection("ddd");
        FindIterable<Document> documents = collection.find();
        MongoCursor<Document> iterator = documents.iterator();

        System.out.println("查询所有文档。。。。");
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    /**
     * 创建文档
     */
    public void test1(){
        MongoCollection<Document> collection = database.getCollection("ddd");

        //创建文档
        Document document = new Document("name", "张康泽").append("ddddd", 3424);


        //文档添加进集合
        collection.insertOne(document);

    }

    /**
     * 更新文档
     */
    public void test2(){
        MongoCollection<Document> collection = database.getCollection("ddd");
        UpdateResult result = collection.updateMany(Filters.eq("id", 101), new Document("$set", new Document("name", "张康泽")));
        long modifiedCount = result.getModifiedCount();
    }

    /**
     * 删除文档
     */
    public void test3(){
        MongoCollection<Document> collection = database.getCollection("ddd");

        DeleteResult result = collection.deleteMany(Filters.eq("id", 103));
        System.out.println("删除条数;\t"+result.getDeletedCount());
    }
}
